//
//  OauthController.swift
//  JGWB
//
//  Created by 付建国 on 2016/10/11.
//  Copyright © 2016年 sher. All rights reserved.
//

import UIKit
import SVProgressHUD

class OauthController: UIViewController {
    
    @IBOutlet weak var loginWebView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNavgatioBar()
        
        loadLoginView()
        
    }
}

// MARK:- 设置UI
extension OauthController{
    
    fileprivate func setupNavgatioBar(){
        //左侧item
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "关闭", style: .plain, target: self, action: #selector(closeItemClick))
        //右侧item
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "填充", style: .plain, target: self, action: #selector(fillItemClick))
        
        title = "登录页面"
    }
    
    fileprivate func loadLoginView(){
        
        let loginUrlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_url)"
        
        guard let loginUrl = URL.init(string: loginUrlString) else{
            return
        }
        
        let request = URLRequest.init(url: loginUrl)
        
        loginWebView.loadRequest(request)
        
    }
}

// MARK:- 时间监听
extension OauthController{
    
    @objc fileprivate func closeItemClick(){
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func fillItemClick(){
        //js代码
        let jsCode = "document.getElementById('userId').value='18304232877';document.getElementById('passwd').value='882705fu'"
        
        loginWebView.stringByEvaluatingJavaScript(from: jsCode)
        
    }
    
}

// MARK:- webview的协议
extension OauthController : UIWebViewDelegate{
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.url else{
            return true
        }
        //URL中获取字符串
        let urlString = url.absoluteString
        
        guard urlString.contains("code=") else {
            return true
        }
        
        //截取code
        let code = urlString.components(separatedBy: "code=").last!
        
        //请求数据获取token
        loadaccessToken(code: code)
        
        return false
    }
    
}

// MARK:- 请求token
extension OauthController{
    
    fileprivate func loadaccessToken(code : String){
        
        NetworkTools.shareInstance.loadAccessToken(code: code) { (result, error) in
            
            if error != nil{
                
                print(error)
                return
            }
            
            guard let person = result else{
                return
            }
            
            // 字典转化成模型对象
            let account = Person.init(dict: person)
            
            // 请求用户信息
            self.loadUserInfo(account: account)
        }
    }
    
    fileprivate func loadUserInfo(account : Person){
        
        guard let accessToken = account.access_token else {
            return
        }
        
        guard let uid = account.uid else {
            return
        }
        
        NetworkTools.shareInstance.loadUserInfo(access_token: accessToken, uid: uid) { (result, error) in
            
            if error != nil{
                
                print(error)
                return
            }
            
            //取得用户信息
            guard let userInfoDic = result else{
                return
            }
            
            account.screen_name = userInfoDic["screen_name"] as? String
            account.avatar_large = userInfoDic["avatar_large"] as? String
            
            //将account对象保存
            NSKeyedArchiver.archiveRootObject(account, toFile: PersonViewModel.shareIntance.accountPath)
            
            //将account复制给单例对象
            PersonViewModel.shareIntance.account = account
            
            //退出当前控制器/显示欢迎界面
            self.dismiss(animated: false, completion: {
                UIApplication.shared.keyWindow?.rootViewController = WelcomeController()
            })
        
            
            
            
            
        }
    }
}
















